/**
 * Created with IntelliJ IDEA.
 * User: zzl
 * Date: 12-12-16
 * To change this template use File | Settings | File Templates.
 */
(function ($, undefined) {

    var DatetimeInput = function (input, options) {
        this.$input = $(input);
        this.options = options;
        this.$picker = $(this.options.picker).clone();
        this.setup();
    };

    var proto = { constructor: DatetimeInput };
    DatetimeInput.prototype = proto;

    proto.setup = function () {
        var me = this;

        me.$picker.datetimePicker({
            precision: me.options.precision
        });
        me.$input.dropdown({
            content: me.$picker,
            triggerEvent: 'focus',
            listeners: {
                beforeShow: function (input) {
                    me.$picker.datetimePicker('setValue', me.$input.val());
                },
                beforeHide: function (input) {
                }
            }
        });
        me.$input.addClass('datetimeInput');

        me.$picker.find('.btnOk,.btnToday').on('click', function () {
            var date = me.$picker.datetimePicker('getValue');
            var precision = me.options.precision;
            var format = precision == 'minute'? 'yy-MM-dd hh:mm':
                    precision == 'day'? 'date': 'datetime';
            var sDate = jsex.formatDate(date, format);
            me.$input.val(sDate).dropdown('hide');
        });
        me.$picker.find('.btnClear').on('click', function () {
            me.$input.dropdown('hide');
            me.$input.val('');
        });
    };

    proto.unload = function() {
        var me = this;
        me.$input.dropdown('unload');
        me.$input.removeClass('datetimeInput');
        me.$input.removeData('datetimeInput');
    };

    $.fn.datetimeInput = $.addPluginFn('datetimeInput', DatetimeInput, {
        precision: 'second'
    });

})(jQuery);